package com.zy.service.bs.impl;

import com.zy.pojo.exceptions.ServiceException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zy.dao.bs.CarDealerDao;
import com.zy.entity.bs.CarDealer;
import com.zy.pojo.query.bs.CarDealerQuery;
import com.zy.pojo.vos.common.PageVo;
import com.zy.service.base.impl.BaseServiceImpl;
import com.zy.service.bs.CarDealerService;
import tk.mybatis.mapper.entity.Example;

@Service("carDealerService")
public class CarDealerServiceImpl extends BaseServiceImpl<CarDealer> implements CarDealerService {

	@Autowired
	private CarDealerDao carDealerDao;

	@Override
	public PageVo pageCarDealer(CarDealerQuery carDealerQuery, Integer start, Integer limit) {
		return new PageVo(start, limit, this.carDealerDao.countCarDealer(carDealerQuery), this.carDealerDao.listCarDealer(carDealerQuery, start, limit));
	}

	@Override
	public void saveCarDealer(CarDealer carDealer) {
		carDealer.setId(null);
		existsName(carDealer);
		this.carDealerDao.save(carDealer);
	}
	
	@Override
	public void updateCarDealer(CarDealer carDealer) {
		existsName(carDealer);
		this.carDealerDao.updateByPrimaryKeySelective(carDealer);
	}

	@Override
	public void removeCarDealer(long id) {
		try {
			this.carDealerDao.removeByPrimaryKey(id);
		} catch (Exception e) {
			log.info(e.getMessage(),e);
			CarDealer carDealer = new CarDealer();
			carDealer.setId(id);

			this.carDealerDao.updateByPrimaryKeySelective(carDealer);
		}
	}

	@Override
	public void recover(long id) {
		CarDealer carDealer = new CarDealer();
		carDealer.setId(id);

		this.carDealerDao.updateByPrimaryKeySelective(carDealer);
	}
	private void existsName(CarDealer carDealer) {
		Example ex = new Example(CarDealer.class);
		Example.Criteria cr = ex.createCriteria();
		cr.andEqualTo("name", carDealer.getName());
		CarDealer pojo = carDealerDao.getByExample(ex);
		if (pojo != null && !pojo.getId().equals(carDealer.getId())) {
			throw new ServiceException(carDealer.getName()+"重复车行名");
		}

	}

}
